/**
 * 在这里定义和用户相关的路由处理函数，供 /api/login.js 模块进行调用
 */
const CryptoJS = require("crypto-js");
const secretKey = 'math_service*123$'
const { handleQuery } = require('../db/index')
const { createToken, blob2String } = require('../utils/index')
const request = require('request')
// 解密函数
function Decrypt (ciphertext) {
  const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey)
  return bytes.toString(CryptoJS.enc.Utf8)
}
// 更新登录日志
function setLogin (name) {
  handleQuery('insert into login set ?', { name, date: Date.now() })
}
// 管理端登录或注册
exports.login = (req, res) => {
  const { name, password, passwordRe } = req.body
  let str;
  if (passwordRe) {
    // 注册
    str = 'insert into user set ?'
  } else {
    // 登录
    str = 'select * from user where name = ?'
  }
  handleQuery(str, passwordRe ? { name, pwd: password } : [name]).then((data) => {
    if (passwordRe) {
      const success = data.affectedRows === 1
      const mid = {
        code: success ? 200 : 0,
        data: success ? '注册成功' : '注册失败',
      }
      if (success) {
        mid.token = createToken(name)
      }
      res.send(mid)
    } else {
      if (data.length !== 1) {
        res.send({
          code: 0,
          data: '用户名或密码错误',
        })
      } else {
        const { pwd, role, avatar } = data[0]
        const pwd1 = Decrypt(pwd)
        const pwd2 = Decrypt(password)
        const success = pwd1 === pwd2
        const mid = {
          code: success ? 200 : 0,
          data: success ? '登录成功' : '登录失败',
        }
        if (success) {
          mid.token = createToken(name)
          mid.role = role
          if (avatar) {
            const buffer = new Buffer.from(avatar);
            const basebuffer = buffer.toString()
            mid.avatar = basebuffer
          }
        }
        res.send(mid)
      }
    }
    setLogin(name)
  }).catch((err) => {
    console.log(err);
    res.send({
      code: 0,
      data: passwordRe ? '注册失败' : '登录失败'
    })
  })
}
// 管理端用户名查重
exports.checkName = async (req, res) => {
  try {
    const data = await handleQuery('select * from user where name = ?', req.params.name)
    const isRepeat = data.length !== 0
    res.send({
      code: 200,
      data: !isRepeat
    })
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      data: error
    })
  }
}
// 微信小程序登录传code获取用户信息
const appid = 'wx031af2dc1ae391e4'
const secret = '5ff6cee7203f6cf2ca45d6416069fb86'
const wxurl = 'https://api.weixin.qq.com/sns/jscode2session'
async function saveUser (name) {
  try {
    const res = await handleQuery('select * from user where name = ?', name)
    if (!res.length) {
      await handleQuery('insert into user (name) values (?)', name)
    }
    setLogin(name)
    return Promise.resolve(res?.[0] || {})
  } catch (error) {
    return Promise.reject(error)
  }
}
async function sendAction (res, id) {
  try {
    const { avatar, nickname } = await saveUser(id)
    const mid = { openid: id }
    mid.token = createToken(id)
    if (avatar) {
      mid.avatar = avatar
      blob2String(mid)
    }
    if (nickname) {
      mid.nickName = nickname
    }
    res.send(mid)
  } catch (error) {
    res.send({
      code: 0,
      error
    })
  }
}
// 小程序获取唯一标识
exports.getOpenId = (req, res) => {
  if (req.headers['x-wx-openid']) {
    console.log('请求头包含唯一标识', req.headers['x-wx-openid']);
    sendAction(res, req.headers['x-wx-openid'])
  } else {
    request(`${wxurl}?appid=${appid}&secret=${secret}&js_code=${req.params.code}&grant_type=authorization_code`, { rejectUnauthorized: false }, async (error, response, body) => {
      console.log('--------------response----------------');
      console.log(response);
      const mid = JSON.parse(body)
      console.log('--------------body----------------');
      console.log(mid);
      if (mid.openid) {
        // 如果是新用户，需要存入数据库
        sendAction(res, mid.openid)
      } else {
        res.send({
          code: 0,
          data: '获取用户唯一标识失败'
        })
      }
    })
  }
}